package com.project.smarthome.base;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import com.sds.smarthome.foundation.util.XLog;


/**
 * 处理全局的UI提示：当前界面弹出提示、View、Dialog等等
 */
public class ActivityObserver implements Application.ActivityLifecycleCallbacks {

    private Activity mTopActivity;
    private int mActivityCount = 0;
    private long mBackTime = System.currentTimeMillis();


    private AppCallback mAppCallback;

    public ActivityObserver() {
    }

    public Activity getmTopActivity() {
        return mTopActivity;
    }

    public void setAppCallback(AppCallback appCallback) {
        mAppCallback = appCallback;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//        XLog.f("onActivityCreated:" + activity);
//        if (activity instanceof WelcomeActivity || activity instanceof MainActivity) {
//            SmartApplication.sIsnormalstart = true;
//        }
//        if (activity instanceof EquesCallActivity || (activity instanceof GestureVerActivity && PushServiceHandler.sIsCalling)) {
//            XLog.f("onActivityCreated:" + activity +"return");
//            return;
//        }
//        XLog.f("onActivityCreated:" + activity +"start");
//        if (!(activity instanceof WelcomeActivity || activity instanceof MainActivity)
//                && !SmartApplication.sIsnormalstart) {
//            activity.startActivity(new Intent(activity, WelcomeActivity.class));
//            activity.finish();
//        }
//        if (activity instanceof WelcomeActivity) {
//            mTopActivity = activity;
//        }
    }

    @Override
    public void onActivityStarted(Activity activity) {

        mActivityCount++;
        if (mActivityCount == 1) {
            if (mAppCallback != null)
                mAppCallback.onAppForeground(System.currentTimeMillis() - mBackTime);
        }
    }


    @Override
    public void onActivityResumed(Activity activity) {
        XLog.f("onActivityResumed:" + activity);
        mTopActivity = activity;
    }

    @Override
    public void onActivityPaused(Activity activity) {
        XLog.f("onActivityPaused:" + activity);
    }

    @Override
    public void onActivityStopped(Activity activity) {
        XLog.f("onActivityStopped:" + activity);
        mActivityCount--;
        if (mActivityCount <= 0) {

            mBackTime = System.currentTimeMillis();
            if (mAppCallback != null) {
                mAppCallback.onAppBackground();
            }
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }


    @Override
    public void onActivityDestroyed(Activity activity) {
       XLog.f("onActivityDestroyed:" + activity);
    }

    interface AppCallback {
        void onAppForeground(long backTime);

        void onAppBackground();
    }
}
